package org.afeng;

import java.util.Random;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static org.afeng.Game.enterGame;

/**
 * @description:
 * @author: liqf
 * @create: 2022-06-04 23:37
 **/
public class Home {

    static Scanner scanner = new Scanner(System.in);

    // 倒计时时间3秒=3000毫秒
    final static int time = 3000;

    // 变化量 毫秒
    final static int delat = 100;

    // 困难
    final static int delat_2 = 200;

    static ExecutorService executorService = Executors.newSingleThreadExecutor();

    public static void main(String[] args) {

        System.out.println("本程序用来训练反应能力, 游戏开始每个选择默认3秒,之后每条减去0.1或者0.2秒.");
        while (true) {
            System.out.println("选择通关难度: 1-困难,2-轻松,3-退出");
            if (scanner.hasNextLine()) {
                String s = scanner.nextLine();
                if ("1".equals(s)) {
                    createTask(time, delat_2);
                }
                if ("2".equals(s)) {
                    createTask(time, delat);
                }
                if ("3".equals(s)) {
                    break;
                }
            }
        }
        executorService.shutdown();
    }

    /**
     * 创建游戏任务
     *
     * @param tatolTime 初始化允许最大时间
     * @param delat 每次减少时间
     */
    private static void createTask(int tatolTime, int delat) {

        // 初始分
        int count = 0;

        while (true) {
            tatolTime = tatolTime - delat;
            // todo 注意观察count的线程安全问题
            // 下一题
            Future<?> submit = executorService.submit(Game::enterGame2);
            try {
                // todo submit线程超时, 任务怎么处理?
                Object o = submit.get(tatolTime, TimeUnit.MILLISECONDS); // 两线程同步

                // 成功 分成按错, 正确, 正确+1
                if (o instanceof Integer) {
                    if ((int) o == -1) {
                        throw new TimeoutException();
                    }
                    count = count + (int)o;
                }
            } catch (InterruptedException e) {

            } catch (ExecutionException e) {

            } catch (TimeoutException e) {
                // 按错or超时
                System.out.println("得分:"+count);
                break;
            }
        }
    }

    // redis的top



}

